import md5 from 'md5'
import fetch from 'node-fetch'

/**
 * 米游社API调用类
 */
export default class MysApi {
  constructor(uid, cookie, options = {}) {
    // 确保 uid 是字符串
    if (typeof uid === 'object' && uid !== null) {
      // 如果传入对象，根据游戏类型取对应的 uid
      const game = options.game || 'gs'
      this.uid = uid[game] || String(uid)
    } else {
      this.uid = String(uid)
    }
    
    this.cookie = cookie
    this.game = options.game || 'gs' // gs: 原神, sr: 星铁
    this.server = this.getServer(this.uid)
    this.device = options.device || `MysSign-${md5(this.uid).substring(0, 8)}`
    this.timeout = options.timeout || 10000
  }

  /**
   * 根据UID获取服务器区域
   */
  getServer(uid) {
    const _uid = String(uid)
    const firstChar = _uid[0]
    
    const serverMap = {
      gs: {
        '5': 'cn_qd01',    // B服
        '6': 'os_usa',     // 美服
        '7': 'os_euro',    // 欧服
        '8': 'os_asia',    // 亚服
        '9': 'os_cht',     // 港澳台服
        'default': 'cn_gf01' // 官服
      },
      sr: {
        '5': 'prod_qd_cn',
        '6': 'prod_official_usa',
        '7': 'prod_official_euro',
        '8': 'prod_official_asia',
        '9': 'prod_official_cht',
        'default': 'prod_gf_cn'
      }
    }

    return serverMap[this.game][firstChar] || serverMap[this.game]['default']
  }

  /**
   * 判断是否国服
   */
  get isCn() {
    return /cn_|_cn/.test(this.server)
  }

  /**
   * 获取DS签名
   */
  getDs(query = '', body = '') {
    const salt = this.isCn 
      ? 'xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs' 
      : 'okr4obncj8bw5a65hbnn5oo6ixjc3l9w'
    
    const t = Math.floor(Date.now() / 1000)
    const r = Math.floor(Math.random() * 900000 + 100000)
    const hash = md5(`salt=${salt}&t=${t}&r=${r}&b=${body}&q=${query}`)
    
    return `${t},${r},${hash}`
  }

  /**
   * 获取请求头
   */
  getHeaders(query = '', body = '') {
    const cn = {
      app_version: '2.40.1',
      User_Agent: `Mozilla/5.0 (Linux; Android 12; ${this.device}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.73 Mobile Safari/537.36 miHoYoBBS/2.40.1`,
      client_type: '5',
      Origin: 'https://webstatic.mihoyo.com',
      X_Requested_With: 'com.mihoyo.hyperion',
      Referer: 'https://webstatic.mihoyo.com/'
    }
    
    const os = {
      app_version: '2.55.0',
      User_Agent: 'Mozilla/5.0 (Linux; Android 11; J9110 Build/55.2.A.4.332; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/124.0.6367.179 Mobile Safari/537.36 miHoYoBBSOversea/2.55.0',
      client_type: '2',
      Origin: 'https://act.hoyolab.com',
      X_Requested_With: 'com.mihoyo.hoyolab',
      Referer: 'https://act.hoyolab.com/'
    }

    const client = this.isCn ? cn : os
    
    // 游戏标识 (gsuid_core 中的 _GAME_NAME)
    const gameNames = {
      gs: 'hk4e',    // 原神
      sr: 'hkrpg'    // 星铁
    }

    const headers = {
      'x-rpc-app_version': client.app_version,
      'x-rpc-client_type': client.client_type,
      'User-Agent': client.User_Agent,
      'Referer': client.Referer,
      'DS': this.getDs(query, body),
      'Cookie': this.cookie
    }
    
    // 国服签到需要添加 x-rpc-signgame 头（关键！）
    if (this.isCn) {
      headers['x-rpc-signgame'] = gameNames[this.game] || 'hk4e'
    }
    
    return headers
  }

  /**
   * 发起HTTP请求
   */
  async request(url, options = {}) {
    const { method = 'GET', body, headers = {} } = options

    // 提取 URL 的 query 参数用于 DS 签名
    let query = ''
    try {
      const urlObj = new URL(url)
      query = urlObj.search.substring(1) // 去掉开头的 '?'
    } catch (e) {
      // 如果 URL 解析失败，使用空字符串
    }

    const requestOptions = {
      method,
      headers: {
        ...this.getHeaders(query, body ? JSON.stringify(body) : ''),
        ...headers
      },
      timeout: this.timeout
    }

    if (body && method === 'POST') {
      requestOptions.body = JSON.stringify(body)
      requestOptions.headers['Content-Type'] = 'application/json'
    }

    try {
      const response = await fetch(url, requestOptions)
      
      if (!response.ok) {
        logger.error(`[签到插件] HTTP ${response.status} ${response.statusText}`)
        return {
          retcode: -1,
          message: `HTTP ${response.status}`
        }
      }

      const data = await response.json()
      return data
    } catch (error) {
      logger.error(`[签到插件][请求失败] ${error.message}`)
      return {
        retcode: -1,
        message: error.message
      }
    }
  }

  /**
   * 获取活动ID
   */
  getActId() {
    const actIds = {
      gs: 'e202311201442471',   // 原神（2023年11月）
      sr: 'e202304121516551'    // 星铁（2023年4月）
    }
    return actIds[this.game] || actIds.gs
  }

  /**
   * 获取签到信息
   */
  async getSignInfo() {
    const actId = this.getActId()
    
    if (this.isCn) {
      // 国服：原神和星铁都用 /event/luna/info
      const url = `https://api-takumi.mihoyo.com/event/luna/info?act_id=${actId}&region=${this.server}&uid=${this.uid}&lang=zh-cn`
      return await this.request(url)
    } else {
      // 海外服：需要区分
      if (this.game === 'sr') {
        // 星铁海外服：/event/luna/os/info
        const url = `https://sg-public-api.hoyolab.com/event/luna/os/info?act_id=${actId}&region=${this.server}&uid=${this.uid}`
        return await this.request(url)
      } else {
        // 原神海外服：/event/sol/info
        const url = `https://sg-hk4e-api.hoyolab.com/event/sol/info?act_id=${actId}&region=${this.server}&uid=${this.uid}`
        return await this.request(url)
      }
    }
  }

  /**
   * 执行签到
   */
  async doSign() {
    const actId = this.getActId()
    
    let url
    if (this.isCn) {
      // 国服：原神和星铁都用 /event/luna/sign
      url = 'https://api-takumi.mihoyo.com/event/luna/sign'
    } else {
      // 海外服：需要区分
      if (this.game === 'sr') {
        // 星铁海外服：/event/luna/os/sign
        url = 'https://sg-public-api.hoyolab.com/event/luna/os/sign'
      } else {
        // 原神海外服：/event/sol/sign
        url = 'https://sg-hk4e-api.hoyolab.com/event/sol/sign'
      }
    }

    const body = {
      act_id: actId,
      region: this.server,
      uid: this.uid,
      lang: 'zh-cn'
    }

    return await this.request(url, { method: 'POST', body })
  }

  /**
   * 获取签到奖励列表
   */
  async getSignRewards() {
    const actId = this.getActId()
    
    if (this.isCn) {
      // 国服：原神和星铁都用 /event/luna/home
      const url = `https://api-takumi.mihoyo.com/event/luna/home?act_id=${actId}&lang=zh-cn`
      return await this.request(url)
    } else {
      // 海外服：需要区分
      if (this.game === 'sr') {
        // 星铁海外服：/event/luna/os/home
        const url = `https://sg-public-api.hoyolab.com/event/luna/os/home?act_id=${actId}`
        return await this.request(url)
      } else {
        // 原神海外服：/event/sol/home
        const url = `https://sg-hk4e-api.hoyolab.com/event/sol/home?act_id=${actId}`
        return await this.request(url)
      }
    }
  }

  /**
   * 获取米游社游戏角色信息
   */
  async getGameRoles() {
    const gameMap = {
      gs: 'hk4e_cn',
      sr: 'hkrpg_cn'
    }

    const url = this.isCn
      ? `https://api-takumi.mihoyo.com/binding/api/getUserGameRolesByCookie?game_biz=${gameMap[this.game]}`
      : `https://api-os-takumi.mihoyo.com/binding/api/getUserGameRolesByLtoken?game_biz=${gameMap[this.game]}`

    return await this.request(url)
  }
}

